package controlleur;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.view.InternalResourceView;

import annuaire.exceptions.BusinessException;
import annuaire.rmi.remotedObject.IRemotedAnnuaire;
import annuaire.rmi.remotedObject.IRemotedUser;

/**
 * Contrôleur responsable de la deconnexion
 * 
 * @author Yannick Lorenzati & Stephanie Malakian
 * 
 */
public class DisconnectControlleur implements Controller {

	/** Logger pour cette classe ainsi que pour ses sous classes */
	protected final Log logger = LogFactory.getLog(getClass());

	/**
	 * Reference vers l'objet distant Annuaire
	 */
	private IRemotedAnnuaire remotedAnnuaire;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.web.servlet.mvc.Controller#handleRequest(javax.servlet
	 * .http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException,
			BusinessException {

		IRemotedUser user = (IRemotedUser) request.getSession().getAttribute(
				"user");

		// deconnexion effective
		if (user != null) {
			user.logout();
			request.getSession().removeAttribute("user");
			request.getSession().removeAttribute("login");

			request.getSession().setAttribute("role",
					IRemotedAnnuaire.roleAnonymous);
		}

		// string url =
		// org.apache.taglibs.standard.tag.rt.core.UrlTag.resolveUrl(,
		// request.getContextPath(), )
		Map<String, Object> myModel = new HashMap<String, Object>();
		myModel.put("url", "/home.htm");
		myModel.put("time", 3);
		myModel
				.put("message",
						"Vous êtes desormais déconnecté, vous allez être redirigé vers l'accueil...");

		return new ModelAndView(new InternalResourceView("jsp/redirect.jsp"),
				"model", myModel);
	}

	/**
	 * @param remotedAnnuaire
	 */
	public void setRemotedAnnuaire(IRemotedAnnuaire remotedAnnuaire) {
		this.remotedAnnuaire = remotedAnnuaire;
	}

	/**
	 * @return
	 */
	public IRemotedAnnuaire getRemotedAnnuaire() {
		return remotedAnnuaire;
	}
}